package com.itheima.system.controller;


import com.github.pagehelper.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.system.pojo.Role;
import com.itheima.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 删除角色
     * @param id
     */
    @PutMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        try {
            roleService.delete(id);
            return new Result(true,StatusCode.OK,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"删除失败");
        }
    }

    /**
     * 添加用户
     * @param role
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Role role){
        try {
            roleService.add(role);
            return new Result(true,StatusCode.OK,"添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"添加失败");
        }
    }

    /**
     * 修改用户
     * @param role
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Role role){
        try {
            roleService.update(role);
            return new Result(true,StatusCode.OK,"修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"修改失败");
        }
    }

    /**
     * 查询全部角色
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(){
        try {
            List<Role> roleList = roleService.findAll();
            return new Result(true,StatusCode.OK,"查询成功",roleList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"查询失败");
        }
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result findPage(@PathVariable  int page, @PathVariable  int size){
        Page<Role> pageList = roleService.findPage(page, size);
        PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
        return new Result(true,StatusCode.OK,"查询成功",pageResult);
    }
}
